package com.qf.openapi2204.es.controller;

import com.qf.openapi2204.common.vo.ResultVo;
import com.qf.openapi2204.es.esvo.ApiTimeCostEsVo;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/es")
public class EsController {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @GetMapping("/avg/{apiname}/{intervalmin}")
    public ResultVo getApiTimeCostAvg(@PathVariable("apiname") String apiname,@PathVariable("intervalmin") Integer intervalmin){

        long end = System.currentTimeMillis();
        // 获取间隔之前的时间戳
        long start = end - 1000 * 60 * intervalmin;

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.matchQuery("apiName", apiname))
                .must(QueryBuilders.rangeQuery("end").gte(start).lte(end));

        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withIndices("openapi-timecost-index")
                .withQuery(boolQueryBuilder)
                .build();

        List<ApiTimeCostEsVo> esVos = elasticsearchRestTemplate.queryForList(searchQuery, ApiTimeCostEsVo.class);

        // 计算匹配数据的 timecost的平均值
        double v = esVos.stream()
                .mapToLong(ApiTimeCostEsVo::getTimecost)
                .average()
                .orElse(0.0);

        return new ResultVo(1,"ok",v);
    }
}
